<template>
  <div class="model-management">
    <a-space style="margin-bottom: 16px">
      <a-button type="primary" @click="handleAdd">新建</a-button>
      <a-button @click="refreshList">刷新</a-button>
    </a-space>

    <a-table :columns="columns" :dataSource="dataList" :pagination="pagination" rowKey="uuid" @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)">编辑</a>
            <a @click="handleJump(record)">数据列表</a>
            <a @click="handleDelete(record)">删除</a>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" @ok="handleSubmit" @cancel="handleCancel">
      <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="模型名称" name="name" required>
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="模型描述" name="dec">
          <a-input v-model:value="formState.dec" />
        </a-form-item>
        <a-form-item label="组态模型" name="configUid">
          <!-- <a-select v-model:value="formState.configUid">
            <a-select-option value="dec9f92c-1ca3-86dd-09b7-29a947288232">演示应用</a-select-option>
            <a-select-option value="network-monitor">网络监控</a-select-option>
          </a-select> -->
          <a-select v-model:value="formState.configUid" @change="changeConfigUid">
            <a-select-option v-for="option in modelOptions" :key="option.ID" :value="option.displayUid">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="组态展示页面" name="PageUUID">
          <!-- <a-select v-model:value="formState.PageUUID">
            <a-select-option value="d4a8ba20-952c-39e0-6d97-0131d95e2b5e">首页</a-select-option>
          </a-select> -->
          <a-select v-model:value="formState.PageUUID">
            <a-select-option v-for="option in pageOptions" :key="option.PageId" :value="option.PageId">
              {{ option.PageName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="采集数量" name="gatherNumber">
          <a-input-number v-model:value="formState.gatherNumber" :min="1" style="width: 100%" />
        </a-form-item>
        <a-form-item label="连接方式" name="OPCUAConnectType">
          <a-select v-model:value="formState.OPCUAConnectType">
            <a-select-option :value="1">TCP</a-select-option>
            <a-select-option :value="2">HTTPS</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="安全策略" name="OPCUASecurityPolicies">
          <a-select v-model:value="formState.OPCUASecurityPolicies">
            <a-select-option :value="1">None</a-select-option>
            <a-select-option :value="2">Basic128Rsa15</a-select-option>
            <a-select-option :value="3">Basic256</a-select-option>
            <a-select-option :value="4">Basic256Sha256</a-select-option>
            <a-select-option :value="5">Aes128Sha256Rsa0aep</a-select-option>
            <a-select-option :value="6">Aes256Sha256RsaPss</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="消息安全模式" name="OPCUASecurityModes">
          <a-select v-model:value="formState.OPCUASecurityModes">
            <a-select-option :value="1">None</a-select-option>
            <a-select-option :value="2">Sign</a-select-option>
            <a-select-option :value="3">Sign&Encrypt</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="身份验证" name="OPCUAAuthModes">
          <a-select v-model:value="formState.OPCUAAuthModes">
            <a-select-option :value="1">匿名</a-select-option>
            <a-select-option :value="2">用户名&密码</a-select-option>
            <a-select-option :value="3">证书</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { cvaiApi } from '/@/api/system/cvai-api';

const router = useRouter();

// 表格列定义
const columns = [
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '模型描述',
    dataIndex: 'dec',
    key: 'dec',
  },
  {
    title: '采集数量',
    dataIndex: 'gatherNumber',
    key: 'gatherNumber',
  },
  {
    title: '连接方式',
    dataIndex: 'OPCUAConnectType',
    key: 'OPCUAConnectType',
    customRender: ({ text }) => (text === 1 ? 'TCP' : 'HTTPS'),
  },
  {
    title: '安全策略',
    dataIndex: 'OPCUASecurityPolicies',
    key: 'OPCUASecurityPolicies',
    customRender: ({ text }) => {
      const policies = {
        1: 'None',
        2: 'Basic128Rsa15',
        3: 'Basic256',
        4: 'Basic256Sha256',
        5: 'Aes128Sha256Rsa0aep',
        6: 'Aes256Sha256RsaPss',
      };
      return policies[text] || 'Unknown';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: '200px',
  },
];

// 数据列表
const dataList = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
});

// 表单状态
const formState = reactive({
  name: '',
  dec: '',
  configUid: '',
  PageUUID: '',
  type: 3,
  gatherNumber: 30,
  OPCUAConnectType: 1,
  OPCUASecurityPolicies: 1,
  OPCUASecurityModes: 1,
  OPCUAAuthModes: 1,
});

// 弹窗状态
const modalVisible = ref(false);
const modalTitle = ref('新增OPCUA设备模型');
const isEdit = ref(false);
const currentUuid = ref('');

// 获取列表数据
const fetchList = async () => {
  try {
    cvaiApi.opcuaModelList({ type: 3 }).then((res) => {
      if (res.code === 0) {
        dataList.value = res.list; // 将数据模型选项存储到 modelOptions 中
        pagination.total = res.list.length;
      }
    });
  } catch (error) {
    message.error('获取列表失败');
    console.error(error);
  }
};

// 刷新列表
const refreshList = () => {
  fetchList();
};

// 处理表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchList();
};

// 新增按钮
const handleAdd = () => {
  resetForm();
  modalTitle.value = '新增OPCUA设备模型';
  isEdit.value = false;
  modalVisible.value = true;
};

//联动调用接口获取List
const changeConfigUid = (value) => {
  cvaiApi.getMonitorDetail({ muid: value }).then((res) => {
    if (res.code == 0) {
      pageOptions.value = res.layer;
    }
  });
};

// 编辑按钮
const handleEdit = (record) => {
  modalTitle.value = '编辑OPCUA设备模型';
  isEdit.value = true;
  currentUuid.value = record.uuid;
  changeConfigUid(record.configUid);
  // 填充表单数据
  Object.keys(formState).forEach((key) => {
    if (record[key] !== undefined) {
      formState[key] = record[key];
    }
  });

  modalVisible.value = true;
};

// 跳转数据列表
const handleJump = (record) => {};

// 删除按钮
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除模型 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        cvaiApi.opcuaModelDel({ uuid: record.uuid }).then((res) => {
          if (res.code == 200) {
            message.success('删除成功');
            refreshList();
          } else {
            message.error('删除失败');
          }
        });
      } catch (error) {
        message.error('删除失败');
        console.error(error);
      }
    },
  });
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      //更新，编辑操作
      const obj = {
        uuid: currentUuid.value,
        data: { ...formState },
      };
      cvaiApi.opcuaModelEdit(obj).then((res) => {
        if (res.code == 200) {
          message.success('编辑成功');
          refreshList();
          modalVisible.value = false;
        } else {
          message.error('编辑失败');
        }
      });
    } else {
      //新增操作
      cvaiApi.opcuaModelAdd(formState).then((res) => {
        if (res.code == 2002) {
          message.success('新建成功');
          refreshList();
          modalVisible.value = false;
        } else {
          message.error('新建失败');
        }
      });
    }
  } catch (error) {
    message.error('操作失败');
    console.error(error);
  }
};

// 取消表单
const handleCancel = () => {
  modalVisible.value = false;
};

// 重置表单
const resetForm = () => {
  Object.keys(formState).forEach((key) => {
    if (key === 'configUid') {
      formState[key] = '';
    } else if (key === 'PageUUID') {
      formState[key] = '';
    } else if (key === 'type') {
      formState[key] = 3;
    } else if (key === 'gatherNumber') {
      formState[key] = 30;
    } else if (key.startsWith('OPCUA')) {
      formState[key] = 1;
    } else {
      formState[key] = '';
    }
  });
};

//组态模型options
const modelOptions = ref([]);
const pageOptions = ref([]);
function getDisplayModelListOptions() {
  cvaiApi.getDisplayModelList().then((res) => {
    modelOptions.value = res.list;
  });
}

// 初始化
onMounted(() => {
  fetchList();
  getDisplayModelListOptions();
  // 处理路由参数
  if (router.currentRoute.value.query.refresh) {
    refreshList();
  }
});
</script>
<style scoped>
.model-management {
  padding: 20px;
  background: #fff;
}
</style>